package com.yxtbd.travel.travelvm.model.api

import android.util.Log
import com.yxtbd.travel.travelvm.model.bean.ApiBaseResult
import com.yxtbd.travel.travelvm.model.bean.ApiResponse
import org.json.JSONObject
import retrofit2.HttpException
import java.io.IOException

/**
 * description ： BaseRepository
 *
 * author : taodq
 * date : 2020/3/30 17:33
 */
open class BaseRepository {

    suspend fun <T : Any> apiCall(call: suspend () -> ApiResponse<T>): ApiResponse<T> {
        return call.invoke()
    }

    suspend fun <T : Any> safeApiCall(
        call: suspend () -> ApiBaseResult<T>,
        errorMessage: String
    ): ApiBaseResult<T> {
        return try {
            call()
        } catch (e: Exception) {
            Log.e("BaseRepository", e.toString())
            if(e is HttpException){
                val jsonObject = JSONObject(e.response()?.errorBody()?.string())
                var ms = jsonObject.getString("error_description")
                return ApiBaseResult.Error(IOException(ms, e))
            }
            ApiBaseResult.Error(IOException(errorMessage, e))

        }
    }
}